<!-- 此界面为管理员端和教师端的预测界面-->
<template>
  <el-card class="chart-container">
    <h3 class="title">🎯 预测</h3>
<!--    筛选条件-->
    <div class="filter-options">
      <el-form inline class="filter-form">
<!--        年份筛选-->
        <el-form-item label="毕业年份">
          <el-select v-model="selectedGrade" placeholder="选择年份" style="width: 200px" clearable>
            <el-option
                v-for="grade in gradeOptions"
                :key="grade"
                :label="grade"
                :value="grade"
            />
          </el-select>
        </el-form-item>
<!--        专业筛选-->
        <el-form-item label="专业">
          <el-select v-model="selectedMajor" placeholder="选择专业" style="width: 200px" clearable>
            <el-option
                v-for="major in majorOptions"
                :key="major"
                :label="major"
                :value="major"
            />
          </el-select>
        </el-form-item>
      </el-form>

<!--      操作按钮-->
      <el-form-item>
        <el-button type="primary" @click="fetchHotKeywords">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </div>

<!--    词云-->
    <WordCloud :words="hotKeywords" />

<!--    AI建议-->
    <el-button
        type="primary"
        @click="openDialog"
        class="ai-btn fancy-button"
    >💡 AI预测</el-button>

<!--    AI对话框-->
    <el-dialog
        v-model="dialogVisible"
        title="AI预测 (内容由AI生成，请仔细甄别)"
        width="50%"
        class="chat-dialog"
    >
      <div class="chat-box">
        <!-- 消息展示区 -->
        <div v-for="(msg, idx) in messages" :key="idx" :class="['message', msg.role]">
          <div v-if="msg.role === 'assistant'" class="ai-tag">AI</div>
          <div class="msg-content">
            <div v-if="msg.role === 'assistant'" v-html="parseMarkdown(msg.content)"></div>
            <div v-else>{{ msg.content }}</div>
          </div>
        </div>
        <div v-if="loading" class="loading">✨ AI 正在分析中...</div>
      </div>

      <template #footer>
        <el-input
            v-model="userInput"
            placeholder="请输入你的问题（如“推荐几个研究方向”）"
            :disabled="loading"
            @keyup.enter="sendMessage"
        >
          <template #append>
            <el-button :loading="loading" @click="sendMessage">发送</el-button>
          </template>
        </el-input>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import WordCloud from '../../components/WordCloud.vue'
import { marked } from 'marked'
import {
  getAiPredictByKeywords,
  getAllMajors,
  getAllCompletionYears,
  getTop15Keywords
} from "../../api/facultyAdmin.js";

/*
  词云部分
 */
const gradeOptions = ref([]) // 毕业年份
const majorOptions = ref([]) // 专业
const hotKeywords = ref([]) // Top15关键词
const selectedGrade = ref(null) // 当前选择毕业年份
const selectedMajor = ref(null) // 当前选择专业

// 获取所有毕业年份
const fetchAllCompletionYears = async () => {
  try {
    const res = await getAllCompletionYears();
    gradeOptions.value = res.data;
    console.log("所有毕业年份：",gradeOptions.value)
  } catch (e) {
    ElMessage.error('毕业年份获取失败')
  }
}

// 获取所有专业
const fetchAllMajors = async () => {
  try {
    const res = await getAllMajors();
    majorOptions.value = res.data;
    console.log("所有专业：",majorOptions.value)
  } catch (e) {
    ElMessage.error('专业获取失败')
  }
}

// 根据筛选条件初始化关键词
const fetchHotKeywords = async () => {
  try {
    console.log(selectedGrade.value)
    console.log(selectedMajor.value)
    const res = await getTop15Keywords({
      major: selectedMajor.value,
      grade: selectedGrade.value
    })
    hotKeywords.value = res.data.slice(0, 15).map(item => ({
      name: item.keyWord,
      value: item.count || Math.floor(Math.random() * 100 + 20)
    }))
  } catch (e) {
    ElMessage.error('关键词获取失败')
  }
}

// 重置筛选条件
const resetFilters = () => {
  selectedGrade.value = null
  selectedMajor.value = null
  fetchHotKeywords()
}

/*
  AI部分
 */
const dialogVisible = ref(false) // 弹窗状态
const messages = ref([])
const userInput = ref('')
const loading = ref(false)

// markdown 转 html
const parseMarkdown = (text) => marked(text || '')

// 打开对话框并获取初始预测
const openDialog = async () => {
  dialogVisible.value = true
  messages.value = []   // 清空历史
  loading.value = true

  try {
    const res = await getAiPredictByKeywords() // 第一次不带问题
    if (res.code === 1) {
      // 直接使用 res.data 就是 AI 的分析内容
      messages.value.push({ role: 'assistant', content: res.data })
    } else {
      messages.value.push({ role: 'assistant', content: '❌ AI预测失败' })
    }
  } catch (e) {
    console.error(e)
    messages.value.push({ role: 'assistant', content: '⚠️ 请求出错，请稍后再试' })
  } finally {
    loading.value = false
  }
}

// 发送用户问题
const sendMessage = async () => {
  if (!userInput.value.trim()) return

  // 添加用户消息
  messages.value.push({ role: 'user', content: userInput.value })
  const query = userInput.value
  userInput.value = ''
  loading.value = true

  try {
    const res = await getAiPredictByKeywords({ query })
    if (res.code === 1) {
      messages.value.push({ role: 'assistant', content: res.data })
    } else {
      messages.value.push({ role: 'assistant', content: '❌ AI接口调用失败' })
    }
  } catch (e) {
    messages.value.push({ role: 'assistant', content: '⚠️ 请求出错，请稍后再试' })
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await Promise.all([fetchAllCompletionYears(), fetchAllMajors()]) // 先获取毕业年份和专业
  await fetchHotKeywords(); // 最后加载关键词
});
</script>

<style scoped>
@import 'github-markdown-css/github-markdown.css';

.chat-box {
  max-height: 400px;
  overflow-y: auto;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.message {
  display: flex;
  margin-bottom: 10px;
}

.msg-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 15px;
  line-height: 1.5;
  word-break: break-word;
}
/* 让 markdown 样式生效 */
.message.assistant .msg-content {
  background-color: #f4f4f4;
  padding: 12px 16px;
  border-radius: 12px;
  color: #333;
  text-align: left; /* 添加这一行 */
}

.message.assistant .msg-content {
  /* markdown 样式类 */
  @apply markdown-body;
}

.message.user .msg-content {
  background-color: #409eff;
  color: white;
  border-bottom-right-radius: 0;
}

.ai-tag {
  background: #409EFF;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 12px;
  align-self: flex-start;
}
.loading {
  text-align: center;
  color: #999;
  padding: 10px;
}

.fancy-button {
  background: linear-gradient(to right, #409EFF, #66b1ff);
  color: #fff;
  border: none;
  padding: 10px 18px;
  font-size: 15px;
  font-weight: bold;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
  transition: all 0.3s ease;
}

.fancy-button:hover {
  background: linear-gradient(to right, #66b1ff, #409EFF);
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.5);
}

</style>
